/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package javafxmltest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.concurrent.Task;

/**
 *
 * @author Arttu
 */
public class FileDigest extends Task<String> {
    
    private final File file;
    
    public FileDigest(File file) {
        this.file = file;
    }
    
    private String readAndDigestFile() {
        
        MessageDigest md;
        String result = "";
        long size = file.length();
        
        try {
            
            md = MessageDigest.getInstance("MD5");
            
            try (InputStream is = Files.newInputStream(file.toPath())) {

                DigestInputStream dis = new DigestInputStream(is, md);
                byte[] buff = new byte[2048];
                
                int content;
                long read = 0;
                while((content = dis.read(buff)) != -1) {
                    
                    read += content;
                    updateProgress(read, size);
                    
                }
                
            } catch (IOException ex) {
                Logger.getLogger(FileDigest.class.getName()).log(Level.SEVERE, null, ex);
            } 
            
            byte[] digest = md.digest();
            
            for (int i=0; i < digest.length; i++) {
                result += Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 );
            }
            
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(FileDigest.class.getName()).log(Level.SEVERE, null, ex);
        }
            
        return result;
    }

    @Override
    protected String call() throws Exception {
        return readAndDigestFile();
    }
    
}
